use sea_orm::entity::prelude::*;
use sea_orm::{Database, EntityTrait, ActiveModelTrait, Set, NotSet, TryIntoModel};
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::Utc;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "test_vehicles")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: String,
    pub name: String,
    pub max_weight: Decimal,
    pub max_volume: Decimal,
    pub created_at: DateTime,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    println!("🧪 Testing SeaORM with Decimal types...");
    
    // 连接数据库
    let db = Database::connect("mysql://root:root@localhost:3306/tms").await?;
    
    // 创建测试表
    println!("📝 Creating test table...");
    let create_table_sql = r#"
        CREATE TABLE IF NOT EXISTS test_vehicles (
            id VARCHAR(36) PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            max_weight DECIMAL(10,2) NOT NULL,
            max_volume DECIMAL(10,2) NOT NULL,
            created_at DATETIME NOT NULL
        )
    "#;
    
    db.execute_unprepared(create_table_sql).await?;
    
    // 清空表
    db.execute_unprepared("DELETE FROM test_vehicles").await?;
    
    println!("✅ Test table created and cleared");
    
    // 测试插入
    println!("🔄 Testing insert with Decimal...");
    let id = Uuid::new_v4().to_string();
    let now = Utc::now().naive_utc();
    
    let vehicle = ActiveModel {
        id: Set(id.clone()),
        name: Set("Test Vehicle".to_string()),
        max_weight: Set(Decimal::from_f64_retain(15.5).unwrap()),
        max_volume: Set(Decimal::from_f64_retain(60.0).unwrap()),
        created_at: Set(now),
    };
    

    
    // 方法1: 使用 Entity::insert
    println!("📥 Method 1: Using Entity::insert()...");
    match Entity::insert(vehicle.clone()).exec(&db).await {
        Ok(result) => {
            println!("✅ Entity::insert successful!");
            println!("   Insert result: {:?}", result);
            
            // 获取插入的记录
            match Entity::find_by_id(&id).one(&db).await {
                Ok(Some(record)) => {
                    println!("   ID: {}", record.id);
                    println!("   Name: {}", record.name);
                    println!("   Max Weight: {}", record.max_weight);
                    println!("   Max Volume: {}", record.max_volume);
                }
                Ok(None) => println!("   ❌ Record not found after insert"),
                Err(e) => println!("   ❌ Failed to fetch record: {}", e),
            }
        }
        Err(e) => {
            println!("❌ Insert failed: {}", e);
            
            // 方法2: 使用 save (对于新记录)
            println!("📥 Method 2: Using save() for new record...");
            match vehicle.save(&db).await {
                Ok(result) => {
                    println!("✅ Save successful!");
                    // save 返回的也是 ActiveModel，需要转换
                    if let Ok(model) = result.try_into_model() {
                        println!("   ID: {}", model.id);
                        println!("   Name: {}", model.name);
                        println!("   Max Weight: {}", model.max_weight);
                        println!("   Max Volume: {}", model.max_volume);
                    }
                }
                Err(e) => {
                    println!("❌ Save also failed: {}", e);
                }
            }
        }
    }
    
    // 测试查询
    println!("🔍 Testing query...");
    match Entity::find_by_id(&id).one(&db).await {
        Ok(Some(vehicle)) => {
            println!("✅ Query successful!");
            println!("   ID: {}", vehicle.id);
            println!("   Name: {}", vehicle.name);
            println!("   Max Weight: {} (as f64: {})", 
                vehicle.max_weight, 
                vehicle.max_weight.to_f64().unwrap_or(0.0)
            );
            println!("   Max Volume: {} (as f64: {})", 
                vehicle.max_volume,
                vehicle.max_volume.to_f64().unwrap_or(0.0)
            );
        }
        Ok(None) => {
            println!("❌ Vehicle not found");
        }
        Err(e) => {
            println!("❌ Query failed: {}", e);
        }
    }
    
    // 清理测试表
    println!("🧹 Cleaning up...");
    db.execute_unprepared("DROP TABLE test_vehicles").await?;
    
    println!("🎉 Test completed!");
    Ok(())
}